package controller;

import net.sf.json.JSONArray;
import pojo.Cate;
import service.CateManagement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

/**
 * @author: zen
 * @date: 2020/9/11
 * @Title: FuzzyQueryOfCateName
 * @Description: 模糊查询cate
 */

@WebServlet("/getCateListByKey")
public class FuzzyQueryOfCateName extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置响应内容类型（MIME）
        resp.setContentType("text/html;charset=UTF-8");
        String key = "";
        int offset = 0;
        // 获取前端请求参数
        if (req.getParameter("cateName") != null) {
            key = req.getParameter("cateName");
        } else {
            key = "";
        }
        if (req.getParameter("offset") != null) {
            offset = Integer.parseInt(req.getParameter("offset"));
        }
        // 如果传值为未定义，则默认全部查找
        if ("undefined".equals(key)) {
            key = "";
        }
        System.out.printf("key的值是：%s\toffset的值是%s\n", key, offset);
        // 调用service层方法得到数据对象
        ArrayList<Cate> cates = CateManagement.getCatesByKey(key, offset);
        // 将对象转换为JSON数组
        JSONArray array = JSONArray.fromObject(cates);
        // 通过resp对象获取out对象（out对象用户向客户端发送数据）
        PrintWriter out = resp.getWriter();
        // 向客户端发送数据
        out.println(array.toString());
        // 清空流
        out.flush();
        // 关闭输出流
        out.close();

    }

        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doPost(req, resp);
    }
}


